<template>
  <div >
    <div v-show="searchStatus" class="box-shadow pad10 mgb10">
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="fnmb">
        <div class="flex jbetween">
          <div>
            <el-form-item label="编号">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="名称">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </div>
          <div class="flex acneter jend fnw">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <MyTable
      :tableList="tableList"
      :total="Total"
      :columns="columns"
      v-model:page="page"
      v-model:searchStatus="searchStatus"
      :btnList="$checkBtn(['ClassHour:edit', 'ClassHour:delete'])"
      @getList="getList"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <template v-slot:tabTop>
        <el-button
          type="primary"
          icon="CirclePlusFilled"
          v-hasPermi="['ClassHour:add']"
          @click="handleAdd"
          >添加方案</el-button
        >
      </template>
    </MyTable>

    <MyDialog
      v-model:show="show"
      :title="title"
      :formRef="formRef"
      @confirm="confirm"
      :width="1000"
      :destroy="true"
    >
      <el-form
        :model="formData"
        :rules="rules"
        inline
        ref="formRef"
        class="wid100"
        label-width="80px"
      >
        <el-row>
          <MyCol :span="12" :xm="12" :sm="12" :lg="12" :md="12">
            <el-form-item label="方案编号" prop="SchoolTime.Code">
              <el-input
                v-model="formData.SchoolTime.Code"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </MyCol>
          <MyCol :span="12" :xm="12" :sm="12" :lg="12" :md="12">
            <el-form-item label="方案名称" prop="SchoolTime.Name">
              <el-input
                v-model="formData.SchoolTime.Name"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </MyCol>
        </el-row>
        <el-row>
          <el-form-item label="课时方案" prop="SchoolTime_Nodes">
            <div class="fieldSelectBox box-shadow">
              <div class="fieldSelectTitle">
                <div>课时</div>
                <div>上课时间</div>
                <div>下课时间</div>
              </div>
              <el-empty
                v-if="!formData.SchoolTime_Nodes.length > 0"
                style="height: 100px"
                :image-size="50"
                description="暂无数据"
              ></el-empty>
              <div v-else style="margin: 10px 0">
                <div
                  v-for="(iten, index) in formData.SchoolTime_Nodes"
                  :key="index"
                  class="fieldSelectInput"
                >
                  <el-icon
                    :size="28"
                    color="red"
                    class="pointer"
                    @click="handleDeleteIcon(index)"
                    ><Remove
                  /></el-icon>
                  <!-- 
                  <el-input
                    v-model.trim="formData.SchoolTime_Nodes[index]['Name']"
                    placeholder="课节名称"
                  ></el-input> -->
                  <el-input
                    v-model.trim="
                      formData.SchoolTime_Nodes[index]['CourseHour']
                    "
                    v-number="{ args: 'point', dotCount: 2, topNoZero: true }"
                    placeholder="课时"
                  ></el-input>

                  <el-time-picker
                    v-model="formData.SchoolTime_Nodes[index]['StartTime']"
                    
                    placeholder="上课时间"
                    clearable
                    value-format="HH:mm"
                    format="HH:mm"
                  />
                  <el-time-picker
                    v-model="formData.SchoolTime_Nodes[index]['EndTime']"
                    placeholder="下课时间"
                    clearable
                    value-format="HH:mm"
                    format="HH:mm"
                  />
                </div>
              </div>
            </div>
            <div class="addbtn">
              <el-button
                type="text"
                :icon="'CirclePlus'"
                @click="addSelectRange"
                >新增可选项</el-button
              >
            </div>
          </el-form-item>
        </el-row>
      </el-form>
    </MyDialog>
  </div>
</template>

<script setup name="ClassHour">
import {
  GetSchoolTimeList_Page,
  GetSchoolTimeDetail,
  EditSchoolTime,
  DelSchoolTime,
  AddSchoolTime,
} from "@/api/school/classHour.js";
import { getCurrentInstance, onMounted, ref } from "vue";
const { proxy } = getCurrentInstance();
const tableList = ref([]);
const Total = ref(0);
const columns = ref([
  { label: "序号" },
  { label: "编号", prop: "Code" },
  { label: "名称", prop: "Name" },
  { label: "创建时间", prop: "tooltipList" },
  { label: "创建人", prop: "CreateUser", user: true },
  { label: "修改时间", prop: "UpdateTime" },
  { label: "修改人", prop: "UpdateUser", user: true },
  { label: "操作", width: 160 },
]);
proxy.$formatKey(columns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10,
});
const searchStatus = ref(true);
const queryParams = ref({
  Code: "",
  Name: "",
  NoPage: "", //如果传"true"，则返回全部数据不分页
});
const queryRef = ref();
const show = ref(false);
const title = ref();
const formRef = ref();
const formData = ref({
  SchoolTime: {},
  SchoolTime_Nodes: [],
});

//验证输入框
let validateRange = (rule, value, callback) => {
  if (!formData.value.SchoolTime_Nodes?.length)
    return callback(new Error(`${rule.label}不能为空`));
  formData.value.SchoolTime_Nodes?.some((item) => {
    // if (!item.Name) {
    //   return callback(new Error(`课节名称不能为空`));
    // }
    if (!item.CourseHour) {
      return callback(new Error(`课时不能为空`));
    }
    if (!item.StartTime) {
      return callback(new Error(`上课时间不能为空`));
    }
    if (!item.EndTime) {
      return callback(new Error(`下课时间不能为空`));
    }
  });
  // let obj = {};
  // formData.value.SchoolTime_Nodes?.reduce((pre, cur, index) => {
  //   if (!obj[cur]) {
  //     obj[cur] = 0;
  //   }
  //   obj[cur]++;
  // }, {});
  // let same = Object.values(obj)?.some((item) => {
  //   return Number(item) > 1;
  // });
  // if (same) {
  //   return callback(new Error(`${rule.label}不能有重复选项`));
  // } else {
  callback();
  // }
};

const rules = ref({
  "SchoolTime.Name": [{ required: true, message: "请输入", trigger: "blur" }],
  "SchoolTime.Code": [{ required: true, message: "请输入", trigger: "blur" }],
  SchoolTime_Nodes: [
    {
      required: true,
      validator: validateRange,
      trigger: ["blur", "change"],
      label: "课时小节",
    },
  ],
});

function reset() {
  formData.value = {
    SchoolTime: {},
    SchoolTime_Nodes: [],
  };
}

onMounted(() => {
  getList();
});

function handleAdd() {
  show.value = true;
  reset();
  title.value = "添加方案";
}
async function handleEdit(row) {
  try {
    let { data } = await GetSchoolTimeDetail({ ID: row.ID });
    formData.value = {
      SchoolTime: data.Info,
      SchoolTime_Nodes: [...data.Nodes],
    };
    title.value = "修改方案";
    show.value = true;
  } catch (error) {
    console.log(error);
  }
}
async function handleDelete(row) {
  try {
    await DelSchoolTime({ ID: row.ID });
    proxy.$modal.msgSuccess("删除成功");
    getList();
  } catch (error) {
    console.log(error);
  }
}
function resetQuery() {
  queryParams.value = {
    Code: "",
    Name: "",
    NoPage: "",
  };
  proxy.resetForm("queryRef");
  handleQuery();
}
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
async function getList() {
  try {
    let query = {
      ...page.value,
      ...queryParams.value,
    };
    let res = await GetSchoolTimeList_Page(query);
    res.data.List?.forEach((item) => {
      item["tooltipList"] = [item.CreateTime];
    });
    console.log(res.data.List);
    tableList.value = res.data.List;
    Total.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
}

async function confirm(valid) {
  try {
    if (valid) {
      if (title.value.includes("添加")) {
        await AddSchoolTime(formData.value);
        proxy.$modal.msgSuccess("添加成功");
      } else {
        await EditSchoolTime(formData.value);
        proxy.$modal.msgSuccess("修改成功");
      }

      show.value = false;
      getList();
    }
  } catch (error) {
    console.log(error);
  }
}

//删除
const handleDeleteIcon = (index) => {
  //可选范围
  formData.value.SchoolTime_Nodes.splice(index, 1);
  formRef.value.validateField("SchoolTime_Nodes");
};
//添加可选范围
const addSelectRange = () => {
  formData.value.SchoolTime_Nodes.push({
    Name: "",
    Type: "", //类型 1:上午 2:下午
    StartTime: "", //上课时间
    EndTime: "", //下课时间
  });
};
</script>

<style lang="scss" scoped>
.fieldSelectBox {
  border: 1px solid #ddd;
  width: 100%;
  border-radius: 10px;
  .fieldSelectTitle {
    padding-left: 30px;
    background-color: rgb(245, 244, 244);
    color: rgb(124, 122, 122);
    display: grid;
    grid-template-columns: repeat(3,1fr);
    justify-items: center;

    // transform: translateY(-8px);
    left: 24px;
  }
  .addbtn {
    border-top: 1px solid #ddd;
    padding-left: 30px;
  }
  .fieldSelectInput {
    padding: 6px;
    display: flex;
    align-items: center;
    .deleteIcon {
      font-size: 24px;
      color: red;
      margin-right: 10px;
      cursor: pointer;
    }
  }
}
.fillText {
  margin: 0 20px;
  word-break: keep-all;
  white-space: nowrap;
}
</style>
